package com.example.flutter_android_connect

import android.content.Context
import android.view.View
import android.widget.TextView
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

/**
 * 「messenger」：用于消息传递，后面介绍 Flutter 与 原生通信时用到此参数。
 * 「viewId」：View 生成时会分配一个唯一 ID。
 * 「args」：Flutter 传递的初始化参数。
 */
class MyFlutterView(context: Context,messenger:BinaryMessenger,viewId:Int,args:Map<String,Any>?) : PlatformView,MethodChannel.MethodCallHandler {
    private val textView:TextView = TextView(context)
    private var methodChannel:MethodChannel
    init {

        args?.also {
            textView.text = it["text"] as String
        }
//        methodChannel = MethodChannel(messenger, "com.example.flutter_android_connect")
        //原生 View 使用 viewId 构建不同名称的 「MethodChannel」：
        methodChannel = MethodChannel(messenger, "com.example.flutter_android_connect.MyFlutterView_$viewId")
        methodChannel.setMethodCallHandler(this)

    }
    override fun getView(): View {
        return textView
    }
    override fun dispose() {
        methodChannel.setMethodCallHandler(null)

    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "setText") {
            val name = call.argument("name") as String?
            val age = call.argument("age") as Int?

            textView.text = "hello,$name,年龄：$age"
        } else if(call.method == "getData"){
            val name = call.argument("name") as String?
            val age = call.argument("age") as Int?
            var map= mapOf("name" to "hello,$name","age" to "$age")
            result.success(map)
        }

        else {
            result.notImplemented()
        }
    }
}